package tom.spring.cloud.gateway.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.protocol.RequestContent;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * zuul 过滤器, 这里做前置请求过滤
 * @author ZHUFEIFEI
 */
@Slf4j
@Component
public class AccessFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //获取当前请求的上下文 内部是threadLocal
        RequestContext ctx = RequestContext.getCurrentContext();
        //从上下文中获取当前请求
        HttpServletRequest req = ctx.getRequest();
        log.info("request : {} ", req.getRequestURI());
        String token = req.getParameter("token");
        if (StringUtils.isBlank(token)) {
            //
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(HttpStatus.SC_FORBIDDEN);
            log.info("request : {} not permit without token parameter.", req.getRequestURI());
            return null;
        }
        log.info("request : {} permit.", req.getRequestURI());
        return null;
    }
}
